package com.maikec.utils.file;
/**
 * 邢帅教育
 * <p>
 * 本源代码由数据中心及其作者共同所有，未经版权持有者的事先书面授权，
 * 不得使用、复制、修改、合并、发布、分发和/或销售本源代码的副本。
 *
 * @copyright Copyright (c) 2018. [图片]xsteach.com all rights reserved.
 */

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.maikec.utils.mybatis.base.BaseServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author maikec
 * @date 2018/7/28
 */
@Service("fileService")
@Slf4j
public class FileServiceImpl extends BaseServiceImpl<File> implements FileService {
    private static final String FILE_IMAGE = "image";
//    private final FileMapper fileMapper;

//    public FileServiceImpl(FileMapper fileMapper) {
//        this.fileMapper = fileMapper;
//    }

    @Transactional(rollbackFor = Exception.class,timeout = 3600, readOnly = false)
    @Override
    public int saveFile(MultipartFile multipartFile) {
        try {
            File file = new File();
            file.setName(multipartFile.getOriginalFilename());
            file.setContent(Base64.encode(multipartFile.getBytes()));
            file.setSize(multipartFile.getSize());
            if (StrUtil.startWith(multipartFile.getContentType(), FILE_IMAGE)) {
                file.setType(FileEnum.IMAGE.getValue());
            } else {
                file.setType(FileEnum.DOC.getValue());
            }
            file.setContentType(multipartFile.getContentType());
            return insert(file);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("文件保存异常");
        }
//        catch (SQLException e) {
//            e.printStackTrace();
//            log.info("blob 转换异常");
//        }
        return 0;
    }

    @Override
    public File getFile(int id) {
//        File temp = fileMapper.getFileById(id);
//        System.out.println(temp);
        File file = new File();
        file.setId(id);
        file = selectById(file);
        System.out.println(file);
        return file;
    }

}
